import React, {Component} from 'react'
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux'
import { getCarNum } from '../../../actions/headers/index';

var Icon = require('antd/lib/icon')
var Rate = require('antd/lib/rate')
var Button = require('antd/lib/button')
import Message from 'antd/lib/message';
import LazyLoad from 'react-lazyload'
import Link from 'next/link'
import Router from 'next/router'
import {
	basicConfig
} from '../../../static/js/config'
import {
	toDecimal2,
	checkLoginStatus,
	setToken
} from '../../../static/js/global.js'

import PlaceholderComponent from '../../Placeholder'
import ProductModal from '../productItem/pro-modal'

class ProductList extends Component {
	state = {
		showImgIndex: [
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
			0,
		], //大图
		cardLoading: false, //购物车按键状态
		timeHere: 0,
		visible: true,
		product: null,
		totalPrice: 0,
		total: 0
	}

	showImg = (index, indexs) => {
		let a = this.state.showImgIndex
		a[index] = indexs
		this.setState({
			showImgIndex: a
		})
	}

	seeBig = (part, index) => {
		this.props.routerPush({
			pathname: '/detail',
			query: {
				itemId: part.itemId
			}
		})
	}

	addToCart = (part, index) => {
		//切换按钮状态
		this.setState({
			cardLoading: true
		})

		/*itemId price specId quantity*/
		if (part.specList.length > 1 || part.inventory <= 0) {
			this.props.routerPush({
				pathname: '/detail',
				query: {
					itemId: part.itemId
				}
			})
		} else {
			var specId = "0";
		     if(part.specList && part.specList.length == 1){
		        specId = part.specList[0].id;
		     }
			let price = part.discount != null ? part.discount.amount : part.price
			this.props.father.addToCard({
					itemId: part.itemId,
					price: price,
					specId: specId,
					quantity: 1
				})
				.then(res => {
					if (res && res.data.success) {
						//购物车效果
                        this.props.getCarNum();
                        this.setState({
                        	product: part,
                        	visible: true,
				            total:res.data.data.cartCount,
				            totalPrice: res.data.data.cartTotalPrice
                        })
						//Message.success('Add to cart successful !');
					} else {
						Message.error(res.data.message);
						this.setState({
							cardLoading: false
						})
					}
				}).catch((error) => {
					this.setState({
						cardLoading: false
					})
				});
		}

	}

	collect = (action, index) => {
		let listData = this.props.listData
		if (!action.favorited) {
			this.props.father.collectGoods({
					itemId: action.itemId
				})
				.then(res => {
					if (res.data.success) {
                        Message.success('Add Collect Success');
						listData[index].favorited = true
						this.props.father.setDataList(listData);

                    }
				}).catch((error) => {

				});
		} else {
			this.props.father.cancelCollectGoods({
					itemId: action.itemId
				})
				.then(res => {
					if (res.data.success) {
                        Message.success('Cancel Collect Success');
						listData[index].favorited = false
						this.props.father.setDataList(listData);

                    }
				}).catch((error) => {

				});
		}
	}

	cancelHideModal = () => {
	    this.setState({
	      visible: false,
	    });
	  }

	componentDidMount() {
		this.timer = setInterval(() => {
			this.setState({
				timeHere: this.state.timeHere + 1
			})
		}, 1000)
	}

	componentWillUnmount() {
		clearInterval(this.timer)
	}

	render() {
		const {
			listData
		} = this.props
		return (
			<div className='productList'>
				{
					listData.map((part,index)=>(
						<div className='part' key={index}>
							<div className='left-img'>
								<Link href={{ pathname: '/detail', query: { itemId: part.itemId }}}>
									<a>
										<LazyLoad offset={[-200, 0]} placeholder={<PlaceholderComponent />} >
											<img className="img-left" src={part.imageList!=null? part.imageList[this.state.showImgIndex[index]]:''}/>
										</LazyLoad>
									</a>
								</Link>

							</div>
							<div className='right-info'>

								{
									part.discount?
										<div className='sale'>
											<span className='sale-span'>SALE</span>
											<span className='sale-spans'>{`-${(10-part.discount.discountRate).toFixed(2)*10}%`}</span>
										</div> : ''
								}
								{
									part.brokerage?
										<div className='sale'>
											<span className='sale-span'>GET</span>
											<span className='sale-spans'>${part.brokerage}</span>
										</div> : ''
								}
								
								<div className='title'>
									<Link href={{ pathname: '/detail', query: { itemId: part.itemId }}}><a>{part.name}</a></Link>
								</div>
								<div className='comment'>
									<Rate allowHalf disabled defaultValue={part.comment.avgscore} />
								</div>
								<div className='price'>
									<span className='price-symbol'>$</span>
									<span className='price-primary'>{part.discount!=null?(part.priceMin*part.discount.discountRate*0.1).toFixed(2):part.priceMin.toFixed(2)}</span>
									{
										part.discount!=null?<span className='price-sale'>${part.priceMin.toFixed(2)}</span>:''
									}
									{part.discount?<span className="tip-box-type1">{`${(10-part.discount.discountRate).toFixed(2)*10}% off`}</span>:null}
									{part.brokerage?<span className="tip-box-type1">${part.brokerage} GET</span>:null}
								</div>
								<div className='photo'>
									{
										part.imageList?
										(
											part.imageList.map((data,indexs)=>(
												<img key={indexs} className={this.state.showImgIndex[index] == indexs?'img-active':'img-pick'} src={data} onClick={()=>this.showImg(index,indexs)}/>
												))
										):''
										}
								</div>
								{
									part.discount!=null?
										<div className='time'>
											<div>
												<span className='time-jewelry-day'>DAYS</span>
												<span>{Math.floor((part.discount.duration-this.state.timeHere)/(60*60*24))}</span>
												<span className='time-default-day'>DAYS</span>
											</div>
											<div>
												<span className='time-jewelry-day'>HR</span>
												<span>{Math.floor(((part.discount.duration-this.state.timeHere)%(60*60*24))/(60*60))}</span>
												<span className='time-default-day'>HR</span>
											</div>
											<div>
												<span className='time-jewelry-day'>MIN</span>
												<span>{Math.floor((((part.discount.duration-this.state.timeHere)%(60*60*24))%(60*60))/60)}</span>
												<span className='time-default-day'>MIN</span>
											</div>
											<div>
												<span className='time-jewelry-day'>SEC</span>
												<span>{
													Math.floor((((part.discount.duration-this.state.timeHere)%(60*60*24))%(60*60))%60)
												}</span>
												<span className='time-default-day'>SEC</span>
											</div>
										</div> :''
								}
								
								<div className='operate'>
									<Button size="large" type="primary" style={{height:40,width:200}} onClick={()=>this.addToCart(part,index)}>
										<Icon type="shopping-cart" />
										<span>ADD TO CART</span>
									</Button>

									{/*<div className='botton' onClick={()=>this.addToCart(part,index)}>
										<Icon type="shopping-cart" />
										<span>ADD TO CART</span>
									</div>*/}
									<Icon 
									onClick={()=>this.seeBig(part,index)}
									className='icon-eyesss' 
									type="eye-o" />
									<span className="icon-p">
										<Icon 
										onClick={()=>this.collect(part,index)}
										className='icon-heart' 
										type={part.favorited?"heart":"heart-o"}
										/>
									</span>
								</div>
							</div>
						</div>
						))
				}
				<ProductModal
	            show={this.state.visible} 
	            product={this.state.product} 
	            close={this.cancelHideModal} 
	            totalPrice={this.state.totalPrice}
	            total={this.state.total}/>
								
			</div>
		)
	}
}


const mapStateToProps = ({headers}) => ({
    headers
});

const mapDispatchToProps = (dispatch) => {
    return {
        getCarNum: bindActionCreators(getCarNum ,dispatch)
    }
};
export default connect(mapStateToProps, mapDispatchToProps)(ProductList)
